import pymysql
# from dbinfo import dbinfo
from 长不大的孩子.work18.dbinfo import dbinfo

class DataBase(object):
    def __init__(self,
                 host=dbinfo['host'],
                 port=dbinfo['port'],
                 user=dbinfo['user'],
                 password=dbinfo['password'],
                 database=dbinfo['database'],
                 charset=dbinfo['charset']):
        self.host = host
        self.port = port
        self.user = user
        self.password = password
        self.database = database
        self.charset = charset

    def __get_connection(self):
        if not self.database:
            raise RuntimeError('数据库没有找到')
        try:
            self.conn = pymysql.connect(host=self.host,
                                        port=self.port,
                                        user=self.user,
                                        password=self.password,
                                        database=self.database,
                                        charset=self.charset)
        except Exception as e:
            raise RuntimeError('初始化数据库失败，原因是：', e)
        self.cursor = self.conn.cursor()
        return self.cursor

    def execute_sql(self, sql, params=None):
        self.__get_connection()
        self.cursor.execute(sql, params)
        self.conn.commit()
        print('提交成功')

    def close(self):
        try:
            self.cursor.close()
        except Exception as e:
            print('游标关闭异常,原因是：', e)
        try:
            self.conn.close()
        except Exception as e:
            print('关闭数据库异常，原因是：', e)

    def select_sql(self, sql, params=None):
        self.__get_connection()
        self.cursor.execute(sql, params)
        data = self.cursor.fetchone()
        return data

    def select_all(self, sql, params=None):
        self.__get_connection()
        self.cursor.execute(sql, params)
        datas = self.cursor.fetchall()
        return datas


if __name__ == '__main__':
    db = DataBase()
    sql = "select * from students_zbddhz WHERE studentNo = %s;"
    data = db.select_sql(sql, [12])
    print(data)
    db.close()
